﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cmd.TypeConverters
{
    public class EnumConverter : ITypeConverter
    {
        public Type BaseType
        {
            get;
            private set;
        }

        public EnumConverter(Type enumType)
        {
            BaseType = enumType;
        }

        public object ConvertFromString(string value)
        {
            if (!BaseType.IsEnum)
            {
                throw new ArgumentException("T must be an enumerated type");
            }
            if (value == null)
            {
                return null;
            }

            return Enum.Parse(BaseType, value as string, true);
        }

        public string ConvertToString(object value)
        {
            if (value == null)
            {
                return null;
            }
            if (!BaseType.IsEnum)
            {
                throw new ArgumentException("T must be an enumerated type");
            }
            
            return value.ToString();
        }
    }
}
